package com.yn.service.zy.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beust.jcommander.internal.Lists;
import com.sun.xml.internal.bind.v2.TODO;
import com.yn.common.enums.AuditStatusEnum;
import com.yn.common.enums.BooleanEnum;
import com.yn.common.exception.TransitException;
import com.yn.common.model.user.User;
import com.yn.common.model.zy.TCarFleetManageDO;
import com.yn.common.model.zy.TCarManageDO;
import com.yn.common.page.BasePage;
import com.yn.common.request.sc.CarFleetManageRequest;
import com.yn.common.request.sc.CarManageRequest;
import com.yn.service.dao.zy.TCarManageMapper;
import com.yn.service.service.UserService;
import com.yn.service.zy.TCarFleetManageService;
import com.yn.service.zy.TCarManageService;
import com.yn.service.zy.model.dto.TCarManageDTO;
import com.yn.service.zy.model.query.TCarManageQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;


@Service
@Slf4j
public class TCarManageServiceImpl extends ServiceImpl<TCarManageMapper, TCarManageDO> implements TCarManageService {

    @Resource
    private TCarManageMapper tCarManageMapper;
    @Resource
    private TCarFleetManageService tCarFleetManageService;
    @Resource
    private UserService userService;

    /**
     * 分页获取车辆-司机信息
     * @param query
     * @param basePage
     * @return
     */
    @Override
    public IPage<TCarManageDTO> listPage(TCarManageQuery query, BasePage basePage) {
        IPage<TCarManageDTO> page = new Page<>(basePage.getPage(),basePage.getLimit());

        return tCarManageMapper.listPage(query,page);
    }

    /**
     * 获取车辆-司机详情
     * @param id
     * @return
     */
    @Override
    public TCarManageDTO getInfo(Integer id) {
        return tCarManageMapper.getInfo(id);
    }

    /**
     * 批量审核
     * @param carIds
     * @param auditStatus
     */
    @Override
    public void batchAudit(List<Integer> carIds, Integer auditStatus) {
        if (CollectionUtils.isEmpty(carIds)) {
            throw new TransitException("请选择要审核的数据");
        }
        if (ObjectUtils.isEmpty(auditStatus) ||
                !Arrays.stream(AuditStatusEnum.values()).map(AuditStatusEnum::getCode).collect(Collectors.toList()).contains(auditStatus)) {
            throw new TransitException("审核无效，请联系管理员");
        }

        List<TCarManageDO> tCarManageDOList = Lists.newArrayList();

       /* // 获取要审核的数据信息
        LambdaQueryWrapper<TCarManageDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(TCarManageDO::getId,carIds);
        queryWrapper.eq(TCarManageDO::getIsDelTag, BooleanEnum.NO.getCode());
        List<TCarManageDO> tCarManageDOListByIds = tCarManageMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(tCarManageDOListByIds)) {
            throw new TransitException("未获取到审核的数据");
        }*/



        carIds.forEach(item -> {
            TCarManageDO tCarManageDO = new TCarManageDO();
            tCarManageDO.setId(item);
            tCarManageDO.setAuditStatus(auditStatus);
            tCarManageDOList.add(tCarManageDO);
        });

        updateBatchById(tCarManageDOList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDriver(CarManageRequest request, Integer fleetManageId) {
        //获取司机行驶证，驾驶证，保险证明以及电话号码用于校验
        String driverLicense = request.getDriverLicense();
        String drivingLicense = request.getDrivingLicense();
        String insuranceCertificate = request.getInsuranceCertificate();
        String carLinkNumber = request.getCarLinkNumber();
        boolean isDriverLicense = tCarFleetManageService.checkImageUrl(driverLicense);
        boolean isDrivingLicense = tCarFleetManageService.checkImageUrl(drivingLicense);
        boolean isInsuranceCertificate = tCarFleetManageService.checkImageUrl(insuranceCertificate);
        boolean isCarLinkNumber = tCarFleetManageService.checkImageUrl(carLinkNumber);
        if(!( isDriverLicense || isDrivingLicense || isInsuranceCertificate)){
            throw new TransitException("上传的证件有错误");
        }

        if(!isCarLinkNumber){
            throw new TransitException("上传的手机号有错误");
        }
        TCarManageDO one = lambdaQuery().eq(TCarManageDO::getCarLinkNumber, request.getCarLinkNumber()).one();
        if(one != null){
            throw new TransitException("手机号已存在");
        }
        User user = userService.getByPhone(request.getCarLinkNumber());
        TCarManageDO tCarManageDO = new TCarManageDO();
        if(user==null){
            //注册新用户
            User user1 = new User();
            user1.setPhone(request.getCarLinkNumber());
            user1.setAccount(request.getCarLinkNumber());
            user1.setStatus(true);
            user1.setRealName(request.getRealName());
            user1.setCardId(request.getCardId());
            if(request.getSex() != null){
                user1.setSex(request.getSex());
            }
            userService.save(user1);
            tCarManageDO.setAppUserId(user1.getUid());
        }else{
            //更新用户信息，phone，cardId，sex，realname
            user.setPhone(request.getCarLinkNumber());
            user.setCardId(request.getCardId());
            if(request.getSex() != null){
                user.setSex(request.getSex());
            }
            user.setRealName(request.getRealName());
            userService.updateById(user);
            tCarManageDO.setAppUserId(user.getUid());
        }
        TCarFleetManageDO byId = tCarFleetManageService.getById(fleetManageId);
            if(byId == null){
                throw new TransitException("要加入的车队信息有误");
            }
            if(byId.getAuditStatus() != 1){
                throw new TransitException("要加入的车队暂时不存在");
            }
            BeanUtil.copyProperties(request, tCarManageDO);
            tCarManageDO.setFleetManageId(fleetManageId);

            save(tCarManageDO);
    }

    @Override
    public void saveDriver2OtherFleet(Integer fleetManageId) {

    }

    @Override
    public HashMap<Integer, String> getFleetName() {
        List<TCarFleetManageDO> list = tCarFleetManageService.lambdaQuery().eq(TCarFleetManageDO::getIsDelTag, 0)
                .eq(TCarFleetManageDO::getAuditStatus, 1)
                .eq(TCarFleetManageDO::getPostStatus, 1).list();
        if(list == null || list.isEmpty()){
            return new HashMap<>();
        }

        return (HashMap<Integer, String>) list.stream().collect(Collectors.toMap(TCarFleetManageDO::getId, TCarFleetManageDO::getFleetName));
    }
}
